package com.ltmonitor.web.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.FunctionModel;
import com.ltmonitor.entity.Role;
import com.ltmonitor.entity.UserInfo;
import com.ltmonitor.service.IFunctionModelService;
import com.ltmonitor.service.IRoleService;
import com.ltmonitor.service.IUserInfoService;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.vo.TreeNode;

@Controller
@RequestMapping("/role")
public class RoleAction extends PaginateAction {

	@Autowired
	protected IFunctionModelService functionModelServcie;
	@Autowired
	protected IRoleService roleService;
	@Autowired
	protected IUserInfoService userInfoService;
	

	@RequestMapping("/viewList.action")
	public String list()
	{
		return "/role/roleList";
	}
	
	@RequestMapping("/view.action")
	public ModelAndView view(Model model,
			@RequestParam(value = "entityId", defaultValue="0") long id) {

		ModelAndView m = new ModelAndView();
		m.setViewName("/role/editRole");
		try {
			Role t = null;
			if (id >0) {
				t = roleService.load(id);
			}else
			{
				t = new Role();
				t.setCompanyId(this.getOnlineUser().getCompanyId());				
			}
			m.addObject("entity", t);

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addObject("发生错误:"+ex.getMessage());
		}

		return m;
	}
	

	@RequestMapping("/save")
	public String save(Role role, Model m, String strFuncMenu) {
		try {
			if(role.getCompanyId() == 0)
			{
				m.addAttribute("message", "请选择所属企业");
				m.addAttribute("entity", role);
				return "/role/editRole";
			}
			
			if (strFuncMenu != null && strFuncMenu.length() > 0) {
				role.getFuncs().clear();
				String[] funcIdArray = strFuncMenu.split(",");
				Map<Long, Long> funcIdMap = new HashMap<Long, Long>();
				for (String str : funcIdArray) {
					long funcId = Long.parseLong(str);
					FunctionModel func = this.functionModelServcie.load(funcId);
					if (funcIdMap.containsKey(func.getEntityId()) == false) {
						role.getFuncs().add(func);
						funcIdMap.put(func.getEntityId(), func.getEntityId());
					}
				}
				
			} else {
				if(role.getEntityId() == 0)
				{
					m.addAttribute("message", "请选择功能权限");
					m.addAttribute("entity", role);
					return "/role/editRole";					
				}
				Role r = this.roleService.load(role.getEntityId());
				r.setName(role.getName());
				r.setShare(role.isShare());
				r.setRemark(role.getRemark());
				r.setCompanyId(role.getCompanyId());
				role = r;
				//m.addAttribute("message", "请选择功能权限");
			}
			if(role.getOwnerId() == 0)
			{
				role.setOwner(this.getOnlineUser().getName());
				role.setOwnerId(this.getOnlineUser().getEntityId());
			}

			this.roleService.saveOrUpdate(role);
			m.addAttribute("message", "保存成功");
			
		} catch (Exception ex) {
			log.error(ex.getMessage());
			log.error(ex.getStackTrace());
			m.addAttribute("message", "保存失败:" + ex.getMessage());
		}
		m.addAttribute("entity", role);
		return "/role/editRole";
	}
	/**
	 * 假删除
	 * @param entityId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/fakeDelete.action")
	public JsonMessage fakeDelete(long entityId) {
		try {
			boolean res = this.roleService.isRoleAssigned(entityId);
			if(res)
			{
				return jsonFail("角色已分配给用户，不能刪除!");				
			}
			this.roleService.deleteFakeById(entityId);
			return jsonSuccess("记录已被成功刪除!");

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return jsonFail(ex.getMessage());
		}

	}
	

	@RequestMapping("/funcTree.action")
	@ResponseBody
	public List<TreeNode> funcTree(long roleId) {
		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		List<BasicData> bs = this.basicDataService
				.getBasicDataByParentCode("FunctionType");

		Map<String, TreeNode> nodeMap = new HashMap<String, TreeNode>();
		for (BasicData bd : bs) {
			TreeNode node = new TreeNode(bd.getCode(), bd.getName(), "",
					"icon-polygon");
			nodeMap.put(node.getId(), node);
			nodeList.add(node);
		}
		
		UserInfo user = (UserInfo)this.userInfoService.load(this.getOnlineUser().getEntityId());
		List<FunctionModel> funcList  = new ArrayList();
		if (user.isSuperAdmin()) {
			// 如果是超级用户，将加所有权限,可以分配所有管理部门
			String hql = "from FunctionModel where deleted = ?";
			funcList = this.functionModelServcie.query(hql, false);
		} else {
			//否则只显示用户自身所具备的权限
			Role r = user.getRole();
			if (r != null) {
				funcList.addAll(r.getFuncs());
			}
		}
		for (FunctionModel func : funcList) {
			String parentId = func.getParentId() == 0 ? ("" + func
					.getFuncType()) : ("" + func.getParentId());
			TreeNode node = new TreeNode("" + func.getEntityId(),
					func.getDescr(), parentId, "icon-polygon");
			// node.setChildren(null);
			node.setState("open");
			node.setLeaf(true);

			nodeMap.put(node.getId(), node);
			// nodeList.add(node);
		}

		for (TreeNode node : nodeMap.values()) {
			if (node.getPid() != null) {
				TreeNode parentNode = nodeMap.get(node.getPid());
				if (parentNode != null) {
					parentNode.getChildren().add(node);
				}
			}
		}

		// Map checkedDepMap = new HashMap();
		if (roleId > 0) {
			Role u = (Role) this.roleService.load(roleId);
			Set<FunctionModel> funcs = u.getFuncs();
			for (FunctionModel func : funcs) {
				String nodeId = "" + func.getEntityId();
				TreeNode node = nodeMap.get(nodeId);
				if (node != null) {
					node.setChecked(true);
				}
			}
		}

		int index = nodeList.size();
		for(int m = index -1; m >= 0 ; m--)
		{
			TreeNode tn = nodeList.get(m);
			if(tn.getChildren() == null || tn.getChildren().size() == 0)
				nodeList.remove(m);
		}

		return nodeList;

	}

}
